import { Inject, Injectable } from '@nestjs/common';
import { Repository } from "typeorm"
import { InjectRepository } from "@nestjs/typeorm"
import { My, Staff } from "./entities/my.entity"
import { Identity } from "./entities/identity.entity"
import { userInfo, staffDataInfo, setIdentity } from "./inteface/index"
import { utils } from "../config/config.utils"

import { JwtService } from "@nestjs/jwt"

@Injectable()
export class MyService {
    constructor(
        private readonly jwtService: JwtService,
        @InjectRepository(My) private readonly my: Repository<My>,
        @InjectRepository(Staff) private staff: Repository<Staff>,
        @InjectRepository(Identity) private identity: Repository<Identity>,
        @Inject("utils") private utils: utils
    ) { }

    //用户注册
    async register(userInfo: userInfo) {

        try {
            let res = await this.my.createQueryBuilder("user").
                where("user.phone=:phone", { phone: userInfo.phone }).
                orWhere("user.username=:username", { username: userInfo.username }).getMany()

            if (res.length > 0) {
                return {
                    code: 400,
                    mes: "用户注册失败,用户名或电话号码已存在，请重试"
                }
            } else {

                // console.log(userInfo.avator.split("").length>0?userInfo.avator : "default")
                const data = new My()
                data.username = userInfo.username
                data.phone = userInfo.phone
                data.password = userInfo.password
                data.avator = userInfo.avator
                // data.class = userInfo.class
                // data.team = userInfo.team
                let resData = await this.my.save(data)

                if (resData.phone && resData.password) {
                    return this.login(resData.password, resData.phone)
                } else {
                    return {
                        code: 400,
                        mes: "用户注册失败",
                    }
                }

            }
        } catch (err) {
            return {
                code: 400,
                mes: err
            }
        }
    }

    // 获取发布作品的用户
   async getUser() {
        // const data = new My()
        let resdata:{username:string,userId:number}[] = []
         let res = await this.my.find()
         res.forEach(item=>{
            resdata.push({
                username:item.username,
                userId:item.id
            })
         })

         if(res.length>0){

            return{
                code:200,
                mes:"获取用户成功",
                data:resdata
            }
         }else{
            return{
                code:400,
                mes:"获取用户失败",
                data:[]
            }
         }
          
    }

    // 删除用户
    deleteUser(id: number) {
        return this.my.delete(id)
    }

    // 修改用户
    async updateUser(id: number) {
        let data = new My()
        data.username = "陈思妙"
        data.password = "123"

        let res = await this.my.update(id, data)

        if (res.affected > 0) {
            return true
        } else {
            return false
        }

    }

    // 普通用户登录
    async login(password: string, phone: string) {

        let resData = await this.my.createQueryBuilder("user").where("user.password=:password", { password })
            .andWhere("user.phone=:phone", { phone }).getMany()
        if (resData.length == 0) {
            return {
                mes: "登录失败用户不存在",
                code: 400

            }
        }
        let userInfo = resData[0]
        userInfo.createTime = this.utils.dateConversion(userInfo.createTime) as unknown as Date
        let dateData = this.utils.calculateDiffDate(userInfo.createTime)
        // console.log(b)
        let jwtObj = {
            id: userInfo.id,
            phone: userInfo.phone,
            username: userInfo.username
        }
        // return resData
        if (resData.length > 0) {
            return {
                code: 200,
                mes: "登录成功",
                data: {
                    userInfo,
                    access_token: this.jwtService.sign(jwtObj),
                    dateObj: dateData
                }
            }
        } else {
            return {
                code: 400,
                mes: "登录失败"
            }
        }


    }

    // 用户名登录
    async namelogin(username: string, password: string) {

        let resData = await this.my.createQueryBuilder("user").where("user.password=:password", { password })
            .andWhere("user.username=:username", { username }).getMany()
        if (resData.length == 0) {
            return {
                mes: "登录失败用户不存在",
                code: 400

            }
        }
        let userInfo = resData[0]
        userInfo.createTime = this.utils.dateConversion(userInfo.createTime) as unknown as Date
        let dateData = this.utils.calculateDiffDate(userInfo.createTime)
        // console.log(b)
        let jwtObj = {
            id: userInfo.id,
            phone: userInfo.phone,
            username: userInfo.username
        }
        // return resData
        if (resData.length > 0) {
            return {
                code: 200,
                mes: "登录成功",
                data: {
                    userInfo,
                    access_token: this.jwtService.sign(jwtObj),
                    dateObj: dateData
                }
            }
        } else {
            return {
                code: 400,
                mes: "登录失败"
            }
        }
    }

    //员工用户注册
    async staffRegister(data: staffDataInfo) {
        // console.log(data)
        if (!data.staffName) {
            return {
                code: 400,
                mes: "没有给数据，请提交数据好吗"
            }
        } else {

            let staffData = new Staff()
            let res = await this.staff.createQueryBuilder("user").
                where("user.staffName=:staffName", { staffName: data.staffName }).
                orWhere("user.idCard=:idCard", { idCard: data.idCard }).getMany()

                if(res.length>0){
                    // 有就更新,没有就插入
                   return this.updateStateBasicData(data)
                   
                }

          
            staffData.staffName = data.staffName
            staffData.address = data.address
            staffData.gender = data.gender
            staffData.idCard = data.idCard
            staffData.mailbox = data.mailbox
            staffData.age = data.age
            staffData.imageUrl = data.imageUrl,
            staffData.phone = data.phone
            let resData = await this.staff.save(staffData)

            return {
                code: 200,
                mes: "员工注册成功",
                resData
            }
        }
    }

       //更新员工的基本数据
       async updateStateBasicData(data){
        let res = await  this.staff.createQueryBuilder().
        update("staff").set({
            staffName:data.staffName,
            address:data.address,
            gender:data.gender,
            idCard:data.idCard,
            mailbox:data.mailbox,
            age:data.age,
            imageUrl:data.imageUrl,
            phone:data.phone

        }).where("staffId =:staffId",{staffId:data.staffId}).execute()


        if(res.affected>0){
            return {
                code: 200,
                mes: "用户数据更新成功",
            }
        }else{
            return {
                code: 200,
                mes: "用户数据更新失败",
            }
        }
    }

    // 设置用户的身份
    async setIdentity(data: setIdentity) {

        if (!data.staffId) {
            return {
                code: 200,
                mes: "没有给数据，怎么能设置设置身份呢",
                data: []
            }
        } else {

            let result = await this.identity.createQueryBuilder("user").
                where("user.staff_id=:staffId", { staffId: data.staffId }).getMany()

            if (result.length > 0) {
                //更新员工数据
                
               return this.updataStaffData(data)
            }

            let idenData = new Identity()
            idenData.staff_id = data.staffId
            idenData.salary = data.salary
            idenData.power = data.power
            idenData.teamId = data.teamId
            idenData.teamId = data.teamId
            idenData.employeeNo = data.employeeNo
            idenData.job = data.job
            let resData = await this.identity.save(idenData)

            if (!resData) {
                return {
                    code: 400,
                    mes: "身份设置失败,能力有限，请自行检查一下喔"
                }
            }

            // console.log(resData)
            return {
                code: 200,
                mes: "身份设置成功",
                // resData
            }
        }

    }

    // 更新员工职工的数据
    async updataStaffData(data:setIdentity):Promise<{code:number,mes:string}>{
        
        let res = await  this.identity.createQueryBuilder().
        update("identity").set({
            salary:data.salary,
            power:data.power,
            teamId:data.teamId,
            job:data.job
        }).where("staff_id =:staffId",{staffId:data.staffId}).execute()

        if(res.affected>0){
            return {
                code: 200,
                mes: "数据更新成功",
            }
        }else{
            return {
                code: 200,
                mes: "数据更新失败",
            }
        }
    }

    // 员工登录
    async staffLogin(username: string, password: string) {
        // console.log(username,password)
        let resData = await this.staff.createQueryBuilder("user").
            leftJoinAndSelect("user.identity", "identity").
            where("user.staffName=:staffName", { staffName: username })
            .andWhere("identity.password=:password",{password})
            .getOne()
            // console.log(resData)
        if (!resData) {
            return {
                code: 400,
                mes: "用户名或密码不正确"
            }
        } else {
            //格式化时间
            resData.registerTime = this.utils.dateConversion(resData.registerTime) as unknown as Date
            resData.identity.idenCreateTime = this.utils.dateConversion(resData.identity.idenCreateTime) as unknown as Date
            let jwtObj = {
                name:resData.idCard,
                mailbox:resData.mailbox,
                staffId:resData.staffId
            }

            return {
                code: 200,
                mes: "登录成功",
                access_token:this.jwtService.sign(jwtObj),
                data: resData
            }
        }

    }

}
